import 'dart:convert';
import 'dart:convert' as convert;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wallet_utils/dialog/double_dialog.dart';
import 'package:wallet_utils/ht_appbar.dart';
import 'package:wallet_utils/log_util.dart';
import 'package:wallet_utils/login_utils.dart';
import 'package:wallet_utils/test_user_manager.dart';
import 'package:wallet_utils/text_util.dart';
import 'package:wallet_utils/toast.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'bean/login_bean.dart';

///WebView 公共页面
// ignore: must_be_immutable
class WebViewCommon extends StatefulWidget {
  String url;

  ///是否需要title（默认true）
  bool isTitle;

  //页面title
  String title = '';

  WebViewCommon(this.url, {this.isTitle = true, this.title = ''});

  @override
  _WebViewCommonState createState() => _WebViewCommonState();
}

class _WebViewCommonState extends State<WebViewCommon> {
  WebViewController? _controller;
  double lineProgress = 0.0; //进度条进度
  bool hide = false;
  @override
  void initState() {
    if (Platform.isAndroid) {
      // WebView.platform = AndroidWebView();
      WebView.platform=SurfaceAndroidWebView();
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: !widget.isTitle
          ? AppBar(toolbarHeight: 0.w)
          : htCommonAppbar(context,
              title: widget.title,
              bottom: hide
                  ? null
                  : PreferredSize(
                      child: _progressBar(lineProgress, context),
                      preferredSize: const Size.fromHeight(3.0),
                    )),
      body: WebView(
        javascriptMode: JavascriptMode.unrestricted,
        javascriptChannels: //Js����flutter ����
            <JavascriptChannel>{
          // _jsChannel(context),
          JavascriptChannel(
              name: 'alreadyRead',
              onMessageReceived: (JavascriptMessage message) {
                Navigator.pop(context);
              }),
          JavascriptChannel(
              name: 'changeTitle',
              onMessageReceived: (JavascriptMessage message) {
                setState(() {
                  widget.title = message.message;
                });
              }),
          JavascriptChannel(
              name: 'showToast',
              onMessageReceived: (JavascriptMessage message) {
                ToastUtils.showToast(message.message);
              }),
          JavascriptChannel(
              name: 'getProcessLogParam',
              onMessageReceived: (JavascriptMessage message) {
                Map<String, dynamic> map = {
                  'marketId': marketId,
                  'businessId': businessId,
                  'businessLoginId': businessLoginId,
                };
                _controller?.evaluateJavascript(
                    'v.getProcessLogParam(${jsonEncode(map)})');
              }),
          JavascriptChannel(
              name: 'showAlertView',
              onMessageReceived: (JavascriptMessage message) {
                Map<String, dynamic> map =
                    convert.jsonDecode(message.message.toString());
                List list = map["actions"];
                showDialog(
                    context: context,
                    builder: (context) {
                      return DoubleDialog(
                        !TextUtil.isEmpty(map["message"]?.toString())
                            ? map["message"]?.toString()
                            : map["title"]?.toString(),//兼容H5数据赋值
                        title: '提示',
                        yesStr: list[1]["actionTitle"].toString(),
                        noStr: list[0]["actionTitle"].toString(),
                        yesCallback: () {
                          _controller
                              ?.evaluateJavascript('v.isCharge()')
                              .then((value) {
                            Get.back();
                          });
                        },
                      );
                    });
              }),
          JavascriptChannel(
              name: 'getShopInfo',
              onMessageReceived: (JavascriptMessage message) async {
                LoginBean loginBean =
                    LoginBean.fromJson(await LoginUtils.getLoginBean());
                Data? login = loginBean.data;
                String marketId = await LoginUtils.getMarketId();
                String businessLoginId = await LoginUtils.getBusinessLoginId();
                String businessId = await LoginUtils.getBusinessId();
                String businessName = await LoginUtils.getBusinessName();

                ///数据写死记得修改
                String str = json.encode({
                  "accessToken": login?.accessToken ?? "",
                  "businessLessee": {
                    //组户 蛋糕店实体门店
                    "businessBerth": "",
                    "businessId": businessId,
                    "businessName": businessName,
                    "marketId": marketId,
                    "marketName": "",
                    "roleId": [1]
                  },
                  "businessLoginId": businessLoginId,
                  "businessShop": {
                    // 商户
                    "account": "",
                    "businessId": businessId,
                    "businessName": businessName,
                    "marketId": marketId,
                    "roleId": [1],
                    "type": "1"
                  },
                  "account": "",
                  "businessType": 3,
                  "distributionStatus": 0,
                  "isDefault": 0,
                  "refreshToken": login?.refreshToken ?? "",
                  "userPhone": login?.mobile ?? ""
                });
                _controller?.evaluateJavascript('v.getUserData($str)');
              }),
        },
        initialUrl: widget.url,
        gestureNavigationEnabled: false,
        onWebViewCreated: (WebViewController webViewController) {
          _controller = webViewController;
        },
        onProgress: (int progress) {
          print('WebView is loading (progress : $progress%)');
        },
        onPageStarted: (String url) {
          print('Page started loading: $url');
        },
        onPageFinished: (String value) {
          setState(() {
            hide = true;
          });
        },
      ),
    );
  }

  _progressBar(double progress, BuildContext context) {
    return LinearProgressIndicator(
      backgroundColor: Colors.white70.withOpacity(0),
      value: progress == 1.0 ? 0 : progress,
      valueColor: new AlwaysStoppedAnimation<Color>(Colors.blue),
    );
  }

  // ���� JavascriptChannel
  JavascriptChannel _jsChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'check_man_machine', //js ����flutter�ķ�����
        onMessageReceived: (JavascriptMessage message) {});
  }

  ///会员服务协议点击我已阅读返回时间
  JavascriptChannel _memberAgreementCallback(BuildContext context) {
    return JavascriptChannel(
        name: 'alreadyRead',
        onMessageReceived: (JavascriptMessage message) {
          Navigator.pop(context);
        });
  }

  JavascriptChannel _changeTitleCallback(BuildContext context) {
    return JavascriptChannel(
        name: 'changeTitle',
        onMessageReceived: (JavascriptMessage message) {
          setState(() {
            widget.title = message.message;
          });
        });
  }
}
